package com.tiny.gui.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;

import javax.swing.JLabel;

/**
 * Desenha um texto centralizado
 * 
 * @author Erick Zanardo
 *
 */
public class CenteredText extends CenteredObject {
    private String text;
    private Font font;
    private Color color;

    private int x;
    private int y;

    public CenteredText(int width, int height, int startX, int startY, String text, Font font, Color color) {
        super(width, height, startX, startY);
        this.text = text;
        this.font = font;
        this.color = color;
        prepare();
    }

    @Override
    public void prepare() {
        JLabel label = new JLabel();
        label.setFont(font);
        FontMetrics metric = label.getFontMetrics(font);

        int totalWidth = 0;
        for (char c : text.toCharArray()) {
            totalWidth += metric.charWidth(c);
        }

        x = width / 2;
        x -= totalWidth / 2;

        y = height / 2;
        y += metric.getHeight() / 2;

        x += startX;
        y += startY;
    }

    @Override
    public void render(Graphics2D g) {
        g.setFont(font);
        g.setColor(color);
        g.drawString(text, x, y);
    }

    @Override
    public int getX() {
        return x;
    }

    @Override
    public int getY() {
        return y;
    }
}
